package com.example.pages;

import static org.openqa.selenium.support.ui.ExpectedConditions.alertIsPresent;

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import com.example.model.SortedListOf;
import com.example.model.User;

public class UserPage extends InternalPage {
	@FindBy(id = "username")
	public WebElement usernameField;

	@FindBy(name = "email")
	public WebElement emailField;

	@FindBy(id = "password")
	public WebElement passwordField;

	@FindBy(id = "password2")
	public WebElement password2Field;

	@FindBy(name = "submit")
	public WebElement submitButton;

	@FindBy(className = "content")
	public List<WebElement> contentDivs;

	@FindBy(xpath = "//div[@class='content'][2]//tr")
	public List<WebElement> users;

	@FindBy(xpath = "//div[@class='content'][2]")
	public WebElement contentTwo;

	public boolean isOnThisPage() {
		return contentTwo.isDisplayed();
	}

	public void submitForm() {
		submitButton.click();
	}

	public UserPage createUser(User user) {
		usernameField.sendKeys(user.name);
		emailField.sendKeys(user.email);
		passwordField.sendKeys(user.password);
		password2Field.sendKeys(user.password);
		submitButton.click();
		cachedUsers = null;
		return MyPageFactory.getPage(driver, UserPage.class);
	}

	public UserPage deleteUser(User user) {
		for (WebElement row : users) {
			if (user.equals(convertRowtoUser(row))) {
				row.findElement(By.xpath("./td[6]/a")).click();
				waits().until(alertIsPresent()).accept();
				break;
			}
		}
		cachedUsers = null;
		return MyPageFactory.getPage(driver, UserPage.class);
	}

	private SortedListOf<User> cachedUsers;

	public SortedListOf<User> getUsers() {
		if (cachedUsers == null) {
			cachedUsers = new SortedListOf<User>();
			for (WebElement row : users) {
				cachedUsers.add(convertRowtoUser(row));
			}
		}
		return new SortedListOf<User>(cachedUsers);
	}

	private User convertRowtoUser(WebElement row) {
		List<WebElement> cells = row.findElements(By.tagName("td"));
		return new User().withName(cells.get(1).getText())
				.withEmail(cells.get(2).getText())
				.withRole(cells.get(3).getText());
	}
}